package com.zyh.alpacaDemo.order;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.alpacaDemo.order.pojo.OrderRequest;
import com.zyh.alpacaDemo.order.pojo.OrderResponse;
import okhttp3.*;

import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * @Classname AlpacaOrderService
 * @Description TODO()
 * @Date 2025-09-01 21:02
 * @Created by 86177
 */
public class AlpacaOrderService {

    // API配置
    private static final String API_KEY_ID = "CK80NDJQC1LSWE5OZ84L";
    private static final String API_SECRET_KEY = "xd3LVDMWL5ng9abaYoYL1cSMXc1eTATa7X2JiA5a";
    private static final String BASE_URL = "https://broker-api.sandbox.alpaca.markets";

    // HTTP客户端和JSON处理器
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;

    public AlpacaOrderService() {
        // 初始化OkHttp客户端
        this.client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        // 初始化Jackson ObjectMapper，支持Java 8日期时间
        this.objectMapper = new ObjectMapper()
                .registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
    }

    // 创建订单
    public OrderResponse createOrder(OrderRequest orderRequest) throws IOException {
        String accouttId = "85fae14c-0f3c-4789-b8c8-37af34128cec";
        // 1.构建请求URL
        HttpUrl url = HttpUrl.parse(BASE_URL).newBuilder()
                .addPathSegment("v1")
                .addPathSegment("trading")
                .addPathSegment("accounts")
                .addPathSegment(accouttId)
                .addPathSegment("orders")
                .build();
        // 2. 构建Basic Auth认证头
        String credentials = API_KEY_ID + ":" + API_SECRET_KEY;
        String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());

        // 将订单对象转换为JSON字符串
        String jsonBody = objectMapper.writeValueAsString(orderRequest);
        RequestBody body = RequestBody.create(
                jsonBody,
                MediaType.parse("application/json; charset=utf-8")
        );
        // 3. 构建请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("accept", "application/json")
                .addHeader("authorization", authHeaderValue)
                .build();
        //4. 使用OkHttpClient发送同步请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            // 检查HTTP状态码是否成功
            if (!response.isSuccessful()) {
                String errorDetails = response.body() != null ? response.body().string() : "No details";
                throw new IOException("API请求失败: " + response.code() +
                        " " + response.message() + "\n详情: " + errorDetails);
            }

            // 确保响应体不为空
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new IOException("API返回空响应");
            }
            // 一次性读取并解析JSON响应
            return objectMapper.readValue(responseBody.string(), OrderResponse.class);
        }
    }

    public static void main(String[] args) {
        AlpacaOrderService orderService = new AlpacaOrderService();
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.setSymbol("AAPL");
        orderRequest.setSide("buy");
        orderRequest.setType("market");
        orderRequest.setTimeInForce("day");
        orderRequest.setQty(1.0);
        orderRequest.setLimitPrice(150.0);
        orderRequest.setStopPrice(140.0);
        try {
            OrderResponse orderResponse = orderService.createOrder(orderRequest);
            System.out.println("订单创建成功: " + orderResponse.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
